package com.xuhao.android.libsocket.utils;

import android.util.Log;

/**
 * Author:  winds
 * Data:    2018/7/17
 * Version: 1.0
 * Desc:
 */


public class Logger {

    public final static String TAG = " -- Socket -- ";
    private static boolean isDeBug = true;  //isDebug :是用来控制，是否打印日志
    public static int logLevel = Log.DEBUG;

    public static void i(String message) {
        i(TAG, message);
    }

    public static void i(String tag, String message) {
        if (isDeBug) {
            Log.i(tag, message);
        }
    }

    public static void error(Throwable ex) {
        error(TAG, ex);
    }

    public static void error(String tag, Throwable ex) {
        if (logLevel <= Log.ERROR) {
            StringBuffer sb = new StringBuffer();
            String name = getFunctionName();
            StackTraceElement[] sts = ex.getStackTrace();

            if (name != null) {
                sb.append(name + " - " + ex + "\r\n");
            } else {
                sb.append(ex + "\r\n");
            }

            if (sts != null && sts.length > 0) {
                for (StackTraceElement st : sts) {
                    if (st != null) {
                        sb.append("[ " + st.getFileName() + ":" + st.getLineNumber() + " ]\r\n");
                    }
                }
            }
            e(tag, sb.toString());
        }
    }

    /**
     * error等级的日志输出
     *
     * @param tag 标识
     * @param msg 内容
     * @return void 返回类型
     */
    public static void e(String tag, String msg) {
        if (isDeBug) {
            Log.w(tag, msg);
        }
    }

    private static String getFunctionName() {
        StackTraceElement[] sts = Thread.currentThread().getStackTrace();

        if (sts == null) {
            return null;
        }

        for (StackTraceElement st : sts) {
            if (st.isNativeMethod()) {
                continue;
            }

            if (st.getClassName().equals(Thread.class.getName())) {
                continue;
            }

            if (st.getClassName().equals(Logger.class.getName())) {
                continue;
            }

            return "[" + Thread.currentThread().getId() + ": " + st.getFileName() + ":" + st.getLineNumber() + "]";
        }

        return null;
    }
}
